$(function () {
	var $result = $('#result');
	var $code = $('#code');

	function log(content){
		var value = $result.val();
		if(value && value != ''){
			value+='\n';
		}
		value+=content;
		$result.val(value);
	}

	function execute(code){
		chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
            chrome.tabs.sendMessage( tabs[0].id, code, function(response) {
            	if(response !== undefined){log(response);}
          });
 		});
	}

	chrome.runtime.onMessage.addListener(  function(msg, sender, sendResponse) {
		if(msg !== undefined){log(msg);}
	});

	//load data
	var $ul = $('#slist');
	var Codes = {
		init:function(){
			if(!window.localStorage){return;}
			var codes = window.localStorage.codes || '{}';
			this.items = JSON.parse(codes);
			this.refresh();
		},
		refresh:function () {
			$ul.empty();
			var html  = [];
			console.log(this.items);
			$.each(this.items,function (key,code) {
				html.push('<li><a class="title">'+key+'</a><div class="operations"><i class="icon-run"></i></div></li>');
			});
			$ul.html(html.join(''));
		},
		add:function(name,code){
			this.items[name] = code;
			this.codes = localStorage.codes = JSON.stringify(this.items);
			this.refresh();
		},
		get:function (key) {
			return this.items[key];
		}
	};
	
	$ul.delegate('li a','click',(function (e) {
		var key = $(this).text();
		var code = Codes.get(key);
		$code.val(code);
	})).delegate('.icon-run','click',function(){
		$(this).closest('li').find('a').click();
		$('#run-code').click();
	});
	$('#run-code').click(function(){
		if($code.val()==''){return;}
		$result.val('');
		execute($code.val());
	});
	$result.click(function () {
		this.select();
	});
	Codes.init();
});


